package com.lxm.config;

import com.lxm.common.contants.BlogConstants;
import com.lxm.common.contants.ItemConstants;
import com.lxm.entity.BlogType;
import com.lxm.entity.ItemType;
import com.lxm.service.BlogTypeService;
import com.lxm.service.ItemTypeService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ProjectInitializingConfig implements InitializingBean {
    @Resource
    private BlogTypeService blogTypeService;
    @Resource
    private ItemTypeService itemTypeService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 项目预处理方法，就是项目一运行就会执行的方法
     *
     * @throws Exception
     */
    //这个方法会在bean全部初始化后服务器完全启动前执行，
    // 一来不会导致bean没有初始化而造成的错误，二来可以进行缓存预加载等操作。
    @Override
    public void afterPropertiesSet() throws Exception {
        addTypeRedis();
    }

    /**
     * 服务器启动，将博客类型和商品类型存入redis
     */
    private void addTypeRedis() {
        Map<String, String> blogMap = new HashMap<>();
        Map<String, String> ItemMap = new HashMap<>();
        blogTypeService
                .lambdaQuery()
                .select(BlogType::getId, BlogType::getName)
                .list()
                .forEach(type -> blogMap.put(type.getId().toString(), type.getName()));
        itemTypeService
                .lambdaQuery()
                .select(ItemType::getId, ItemType::getName)
                .list()
                .forEach(item -> ItemMap.put(item.getId().toString(), item.getName()));
        stringRedisTemplate.opsForHash().putAll(BlogConstants.BLOG_TYPE_KEY, blogMap);
        stringRedisTemplate.opsForHash().putAll(ItemConstants.ITEM_TYPE_KEY, ItemMap);
    }

}
